/**
 * 显示购物车列表
 */
let stateAll = false

function pickUpInformation(){
  // 1. localstorage获取数据
  let  obtain = localStorage.getItem('CARTS')
  let cartList = JSON.parse(obtain)||[]

// console.log(cartList);
// console.log(cartStr);

 
 let str = `
 <tr>
 <th><input type="checkbox" name="" id="" ${stateAll==true? 'checked':''} onclick="addcheckal()"></th>
 <th>商品图片</th>
 <th>商品信息</th>
 <th>单价</th>
 <th>数量</th>
 <th>总价</th>
 <th>操作</th>
 </tr>
 `

let newList = cartList.map((item,index)=>{
return  `
<tr>

  <td><input type="checkbox" name="checkItem" ${item.state==true? 'checked':''} onclick="radioStatus(${index})"></td>
  <td><img src="${item.dizhi}" alt=""></td>
  <td>${item.titles}</td>
  <td class="danjia">￥${item.singPrice}</td>
  <td class="shuliang">${item.quantity}</td>
  <td class="zongjia">￥${item.singtotalprice}</td>
  <td><span class="span1">移入</span>
  <span class="span2" onclick="onDelete(${item.ids})" >删除</span></td>
 </tr>
`
})
str += newList.join('')

 $('table').html(str)


}
pickUpInformation()//获取数据


//点击删除
function onDelete(id){

  let  obtain = localStorage.getItem('CARTS')
  let cartList = JSON.parse(obtain)||[]

let indexs = cartList.findIndex(item=>item.ids == id)

  cartList.splice(indexs,1)
  localStorage.setItem('CARTS',JSON.stringify(cartList))
  pickUpInformation()

}


// 所有商品的总价
function total_price(){
  let  obtain = localStorage.getItem('CARTS')
  let cartList = JSON.parse(obtain)||[]
  let num = 0
//   cartList.forEach(item=>{
// num +=  item.singtotalprice 
//   })
let allLumpSum =cartList.filter(item =>item.state == true)

allLumpSum.forEach(item=>{
 num +=  item.singtotalprice 
  })

let zongjia = Number(num).toFixed(2)


$('.total-price').html('￥'+zongjia)
pickUpInformation()
}
total_price()


/**
 * 点击返回详情页
 */
$('.shopp').on('click',function(){
  location.href = 'details.html'
})




//全选状态
function addcheckal(){
 let  obtain = localStorage.getItem('CARTS')
  let cartList = JSON.parse(obtain)||[]

  if(stateAll==false){
    stateAll =true
 
  }else if(stateAll ==true){
    stateAll =false
  }

  
  cartList.forEach(item=>{
 
    if(stateAll==false){
      item.state = false
  
   }else if(stateAll==true){
      item.state = true
    
  }
  
    localStorage.setItem('CARTS',JSON.stringify(cartList))
  }) 
  total_price()
 pickUpInformation()

}

// 单选状态
function radioStatus(index){
  let  obtain = localStorage.getItem('CARTS')
  let cartList = JSON.parse(obtain)||[]

if(cartList[index].state==false){
  cartList[index].state =true
 
}else if(cartList[index].state ==true){
  cartList[index].state=false

}


let istrue = cartList.every(item => item.state == true)
if(istrue){
  stateAll=true
 }else{
  stateAll=false
 
}

  localStorage.setItem('CARTS',JSON.stringify(cartList))
  total_price()
  pickUpInformation()
}








